//
//  Service_Root_Controller.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/10/30.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//


#import "Service_Root_Controller.h"
#import "Service_listController.h"
#import "Service_listCell.h"
#import "Service_HomemakingController.h"
#import "Service_DetailController.h"
#import "Service_RootCell.h"
#import "UIColor+Hex.h"
#import "Global.h"
#import "UIImage+ColorToImage.h"
#import "NSString+Conversion.h"
#import "ManagerGlobeUntil.h"
#import "ManagerHttpBase.h"
#import "AppDelegate.h"
#import "MTA.h"
#import "MJRefresh.h"
#import "EmptyPageView.h"
#define KheightForFooterInSection 11
#define khSepLineHight 0.7
@interface Service_Root_Controller ()<UITableViewDataSource,UITableViewDelegate,Service_RootCellDelegate,EmptyPageViewDelegate>
{
    NSInteger _requestPage;//当前请求页
    NSInteger _totalCount;//数据总条数
}
@property (nonatomic,strong)UITableView *serviceRootTableView;
@property (nonatomic,strong)NSMutableArray *category;
@property (strong,nonatomic)EmptyPageView *emptyView;
@property (nonatomic,strong)NSMutableArray *dataSource;
@end

@implementation Service_Root_Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _requestPage = 1;
    self.title=@"服务";
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
    _category=[[NSMutableArray alloc]init];
    _dataSource =[[NSMutableArray alloc]init];
    [self setUpSuberView];
    
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        [self loadStoreInfoData];
        
        
    }else{
            [self showEmptyPageWithStatus:YES emptyType:knoShowEmptyPage];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"服务"];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self showEmptyPageWithStatus:NO emptyType:knoShowEmptyPage];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"服务"];
}
#pragma mark -- button and celldelegate

-(void)buttonClick
{
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        [self loadStoreInfoData];
        [self loadServiceShopsDataWithPage:1 requestCount:kRequestLimit];
    }else{
        [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"网络还没好,请重试~" inView:nil];
    }
}
#pragma mark--Service_RootCellDelegate
- (void)selectedItemWithItemContent:(NSDictionary*)itemDic {
    NSString *itemName = [itemDic objectForKey:@"NAME"];
    NSString *itemCode = [NSString stringTransformObject:[itemDic objectForKey:@"CODE"]];
    if ([itemName isEqualToString:@"家政"]) {
        Service_HomemakingController *homemakeVC=[[Service_HomemakingController alloc]init];
        [self.navigationController pushViewController:homemakeVC animated:YES];
    }else{
        Service_listController *listVc=[[Service_listController alloc]init];
        listVc.code=itemCode;
        listVc.titles=itemName;
        [self.navigationController pushViewController:listVc animated:YES];
    }
}
#pragma mark -- requestData
- (void)loadStoreInfoData {
    //    SIGNATURE			设备识别码
    //    ID			店铺ID
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                              inView:self.view];
    
    ManagerHttpBase *manager=[ManagerHttpBase sharedManager];
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:[NSString stringISNull:mode.storeID] forKey:@"STOREID"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"service/category" success:^(AFHTTPRequestOperation *operation, id responseObject) {
         [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            
            if ([state isEqualToString:@"0"]) {//请求成功
                if (_category.count != [[dataDic objectForKey:@"OBJECT"] count]) {
                    [_category removeAllObjects];
                    [_category addObjectsFromArray:[dataDic objectForKey:@"OBJECT"]];
                }
                if (weakSelf.category.count == 0) {
                    [self showEmptyPageWithStatus:NO emptyType:knoBigClass];
                } else {
                    [self loadServiceShopsDataWithPage:_requestPage requestCount:kRequestLimit];
                }
            } else {
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
                [self showEmptyPageWithStatus:NO emptyType:knoBigClass];
            }

        }
        [self endRefresh];
        
    } failure:^(bool isFailure) {
        [self showEmptyPageWithStatus:NO emptyType:knoBigClass];
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        [weakSelf endRefresh];
    }];
    
    
}
- (void)loadServiceShopsDataWithPage:(NSInteger)page requestCount:(NSInteger)requestCount{
    //    SIGNATURE			设备识别码
    //    ID			店铺ID
    
    ManagerHttpBase *manager=[ManagerHttpBase sharedManager];
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:[NSString stringISNull:mode.storeID] forKey:@"STOREID"];
    [parameter setObject:[NSNumber numberWithInteger:page] forKey:@"PAGENUM"];
    [parameter setObject:[NSNumber numberWithInteger:requestCount] forKey:@"PAGESIZE"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"service/shops" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            
            if ([state isEqualToString:@"0"]) {//请求成功
                _totalCount = [[NSString stringTransformObject:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"TOTALROW"]] integerValue];
                if (_requestPage == 1) {//请求第一页清空数据
                    [weakSelf.dataSource removeAllObjects];
                }
                [_dataSource addObjectsFromArray:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"list"]];
                
                if (weakSelf.dataSource.count == 0) {
                    [weakSelf showEmptyPageWithStatus:NO emptyType:knoBusinessList];
                } else {
                     [weakSelf showEmptyPageWithStatus:NO emptyType:knoShowEmptyPage];
                }
                
            } else {
                [weakSelf.dataSource removeAllObjects];
                [weakSelf showEmptyPageWithStatus:NO emptyType:knoBusinessList];
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
            }
            [_serviceRootTableView reloadData];
        }
        [weakSelf endRefresh];
        
    } failure:^(bool isFailure) {
        [weakSelf.dataSource removeAllObjects];
        [weakSelf showEmptyPageWithStatus:NO emptyType:knoBusinessList];
        [_serviceRootTableView reloadData];
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];
        [weakSelf endRefresh];
    }];
    
    
}

#pragma mark--UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{
    if (section == 0) {
        if (self.category.count == 0) {//服务端返回服务项目为空
            return 0;
        } else {//服务端返回服务项目不为空
            return 1;
        }
    }else{
        return _dataSource.count;
    }
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        static NSString *ID=@"oneSection";
        //2.没有则创建cell
        Service_RootCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
        
        
        if(!cell) {
            cell=[[Service_RootCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
            //取消cell点击状态
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate=self;
        }
        [cell setUpSuberViewWithCategory:_category];
        
        //4.返回cell
        return cell;
        
        
    }else{
        static NSString *cellIdentifier = @"fuwushopscell";
        //2.没有则创建cell
        Service_listCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        
        if(!cell) {
            cell=[[Service_listCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            
            cell.accessoryType = UITableViewCellAccessoryNone;
//            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor whiteColor];
        }
                NSDictionary *dataDic = [self.dataSource objectAtIndex:indexPath.row];
                [cell setSuberViewDataWithDictionary:dataDic];
        //4.返回cell
        return cell;
    }
    
}
#pragma mark--UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section ==0) {
        if (_category.count==0) {
            return 0;
        }else{
            Service_RootCell *cell = (Service_RootCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
            return [cell cellFactHight];
        }
    }else{
        return HightScalar(135);
    }
    
}
//黑条效果
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section ==0) {
        return KheightForFooterInSection;
    }else{
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *views = [[UIView alloc]init];
    views.backgroundColor = [UIColor clearColor];
    return views;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section ==0) {
        return 0;
    }else{
        return HightScalar(50);
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *views = [[UIView alloc]init];
    UIImage *sepLineImage = [UIImage createImageWithColor:[UIColor colorWithHexString:@"#dddddd"] frame:CGRectMake(0, 0, 1, khSepLineHight)];
    //分割线
    UIImageView *sepLineview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, khSepLineHight)];
    sepLineview.image = sepLineImage;
    views.backgroundColor = [UIColor whiteColor];
    [views addSubview:sepLineview];
     //指示标示
    UIImageView * imageView =[[UIImageView alloc]initWithFrame:CGRectMake(0, HightScalar(13), 5, HightScalar(22))];
    imageView.image =[UIImage createImageWithColor:[UIColor colorWithHexString:@"#c52720"] frame:CGRectMake(0, 0, 5,  HightScalar(22))];
    [views addSubview:imageView];
    //标题
    UILabel *title =[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame)+10, khSepLineHight, VIEW_WIDTH-25, HightScalar(50) - 2*khSepLineHight)];
    title.font =[UIFont systemFontOfSize:FontSize(15)];
    title.textColor =[UIColor colorWithHexString:@"#999999"];
    title.text =@"附近商家";
    [views addSubview:title];
    
    UIImageView *imageViewLine =[[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMinX(title.frame)
                                                                             , HightScalar(50)-khSepLineHight
                                                                             , VIEW_WIDTH - CGRectGetMinX(title.frame)
                                                                             , khSepLineHight)];
    imageViewLine.image = sepLineImage;
    
    [views addSubview:imageViewLine];
    return views;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section ==1) {
        [_serviceRootTableView deselectRowAtIndexPath:indexPath animated:YES];
        NSDictionary *dicData=[_dataSource objectAtIndex:indexPath.row];
        Service_DetailController *detailVc=[[Service_DetailController alloc]init];
        detailVc.shopID=[NSString stringTransformObject:[dicData objectForKey:@"ID"]];
        detailVc.shopName=[NSString stringTransformObject:[dicData objectForKey:@"NAME"]];
        detailVc.shopImage=[NSString stringTransformObject:[dicData objectForKey:@"THUMB"]];
        [self.navigationController pushViewController:detailVc animated:YES];
    }
}
#pragma mark - 上拉/下拉  更新数据
-(void)headerRereshing {
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        _requestPage = 1;
         [self loadServiceShopsDataWithPage:_requestPage requestCount:kRequestLimit];
    } else {
        [self endRefresh];
    }
}

-(void)footerRereshing
{
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        if (_requestPage*kRequestLimit < _totalCount) {
            
            _requestPage++;
            [self loadServiceShopsDataWithPage:_requestPage requestCount:kRequestLimit];
        } else {
            
            [self.serviceRootTableView setFooterRefreshingText:@"已加载完全部商家~"];
            
            
            [self endRefresh];
        }
        
    } else {
        [self endRefresh];
    }
    
}
- (void)endRefresh
{
    [self.serviceRootTableView headerEndRefreshing];
    [self.serviceRootTableView footerEndRefreshing];
}

#pragma mark --初始化控件
-(void)setUpSuberView
{
    //数据为空时显示的View
    _emptyView =[[EmptyPageView alloc]initWithFrame:CGRectMake(0, 0,VIEW_WIDTH , VIEW_HEIGHT-64-49) EmptyPageViewType:kServiceRootView];
    _emptyView.backgroundColor=[UIColor whiteColor];
    _emptyView.delegate = self;
    [self.view addSubview:_emptyView];
    [self showEmptyPageWithStatus:NO emptyType:knoShowEmptyPage];
    
    //初始化 tableView
    _serviceRootTableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-64-49) style:UITableViewStylePlain];
    _serviceRootTableView.delegate=self;
    _serviceRootTableView.dataSource=self;
    _serviceRootTableView.backgroundColor = [UIColor clearColor];
    //添加下拉刷新
    [_serviceRootTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //添加上拉加载更多
    [_serviceRootTableView addFooterWithTarget:self action:@selector(footerRereshing)];
    [self.view addSubview:_serviceRootTableView];
    
    UIImage *banderImage = [UIImage imageNamed:@"img_ad"];
    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectZero];
    imageView.image=banderImage;
    imageView.frame = CGRectMake(0, 0, self.view.bounds.size.width, HightScalar(145));
    //imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.backgroundColor = [UIColor whiteColor];
    _serviceRootTableView.tableHeaderView=imageView;
    
}


- (void)showEmptyPageWithStatus:(BOOL)isShow emptyType:(ServiceEmptyPageType)type {
    self.emptyView.hidden = !isShow;
    self.serviceRootTableView.hidden = isShow;
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 0)];
    bottomView.backgroundColor = [UIColor clearColor];
    CGFloat contentHight = HightScalar(80) + HightScalar(20) + HightScalar(18);
    UIImage *logoImage = [UIImage imageNamed:@"s_empty"];
    UIImageView *logoImageView = [[UIImageView alloc]initWithImage:logoImage];
    logoImageView.frame = CGRectMake((VIEW_WIDTH - HightScalar(80))/2
                                     , (HightScalar(200) - contentHight)/2
                                     , HightScalar(80)
                                     , 0);
    [bottomView addSubview:logoImageView];
    UILabel *remindLabel = [[UILabel alloc]initWithFrame:CGRectMake(0
                                                                    , CGRectGetMaxY(logoImageView.frame) + HightScalar(20)
                                                                    , VIEW_WIDTH
                                                                    , 0)];
    remindLabel.text = @"附近暂无商家~";
    remindLabel.font = [UIFont systemFontOfSize:FontSize(16)];
    remindLabel.textColor = [UIColor colorWithHexString:@"#555555"];
    remindLabel.textAlignment =  NSTextAlignmentCenter;
    [bottomView addSubview:remindLabel];
    CGRect frame = bottomView.frame;
    CGRect logoImageViewFrame = logoImageView.frame;
    CGRect remindLabelFrame = remindLabel.frame;
    if (type == knoBusinessList) {//有大类数据，没有商家列表数据
        frame.size.height = HightScalar(200);
        logoImageViewFrame.size.height = HightScalar(80);
        remindLabelFrame.size.height = HightScalar(18);
       
    } else if (type == knoShowEmptyPage) {
        frame.size.height = 0;
        logoImageViewFrame.size.height = 0;
        remindLabelFrame.size.height = 0;
    } else if (type == knoBigClass) {
        frame.size.height = HightScalar(200);
        logoImageViewFrame.size.height = HightScalar(80);
        remindLabelFrame.size.height = HightScalar(18);
    }
    bottomView.frame = frame;
    logoImageView.frame = logoImageViewFrame;
     remindLabelFrame.origin.y = CGRectGetMaxY(logoImageView.frame) + HightScalar(20);
    remindLabel.frame = remindLabelFrame;
     self.serviceRootTableView.tableFooterView = bottomView;
}
@end
